import { reqShopCart, reqDeleteCart, reqChangeChecked } from "@/api"

// 仓库存储数据
const state = {
  cartlist: []
}
// 修改state的唯一手段
const mutations = {
  SHOPCARTLIST(state, cartlist) {
    state.cartlist = cartlist
  }
}
// 处理action，可以书写自己的业务逻辑，也可以处理异步
const actions = {
  async getShopCart({ commit }) {
    let result = await reqShopCart()
    // console.log(result);
    if (result.code == 200) {
      commit('SHOPCARTLIST', result.data)
    }
  },
  // 删除商品
  async deleteCart({ commit }, skuId) {
    let result = await reqDeleteCart(skuId)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 修改商品选中状态
  async updateCheck({ commit }, { skuId, isChecked }) {
    let result = await reqChangeChecked(skuId, isChecked)
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("faile"))
    }
  },
  // 删除所选的所有商品
  deleteAllChecked({ dispatch, state }) {
    let PromiseAll = []
    state.cartlist.forEach(async e => {
      let promise = e.isChecked == 1 ? await reqDeleteCart(e.skuId) : ''
      PromiseAll.push(promise)
    });
    // 删除所有成功; 如果有一个失败，返回即为失败结果
    return Promise.all(PromiseAll)
  },
  //修改全部产品的状态
  updateAllCartChecked({ dispatch, state }, isChecked) {
    //数组
    let promiseAll = [];
    state.carList[0].cartInfoList.forEach((item) => {
      let promise = dispatch("updateCheckedById", {
        skuId: item.skuId,
        isChecked,
      });
      promiseAll.push(promise);
    });
    //最终返回结果
    return Promise.all(promiseAll);
  },

}
// 类似于计算属性
const getters = {
  // cartList() {
  //   return state.cartlist[0] || []
  // }

}

export default {
  state,
  mutations,
  actions,
  getters
}